<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Node.js学习(十一.AJAX技术) | 小何blog (记录美好)</title><meta name="keywords" content="系列🏬,Node.js"><meta name="author" content="六根清静"><meta name="copyright" content="六根清静"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="description" content="学习JavaScript之前要先搞清楚计算机基础，分清与HTML等标记语言的区别，这样能更好的帮我们学习JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="Node.js学习(十一.AJAX技术)">
<meta property="og:url" content="https://liugenqingjing2.coding.me/2021/02/15/Node-js%E5%AD%A6%E4%B9%A0-%E5%8D%81%E4%B8%80-AJAX%E6%8A%80%E6%9C%AF/index.html">
<meta property="og:site_name" content="小何blog (记录美好)">
<meta property="og:description" content="学习JavaScript之前要先搞清楚计算机基础，分清与HTML等标记语言的区别，这样能更好的帮我们学习JavaScript">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://632500.haituie.cn/632500/v2-d7641be9e2e374ea645eefec144b350e_r.jpg">
<meta property="article:published_time" content="2021-02-15T13:49:02.000Z">
<meta property="article:modified_time" content="2021-02-15T14:31:58.065Z">
<meta property="article:author" content="六根清静">
<meta property="article:tag" content="系列🏬">
<meta property="article:tag" content="Node.js">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://632500.haituie.cn/632500/v2-d7641be9e2e374ea645eefec144b350e_r.jpg"><link rel="shortcut icon" href="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20200907/wOu*ZmuVb5A4.png"><link rel="canonical" href="https://liugenqingjing2.coding.me/2021/02/15/Node-js%E5%AD%A6%E4%B9%A0-%E5%8D%81%E4%B8%80-AJAX%E6%8A%80%E6%9C%AF/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin="crossorigin"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?e829919a4d931d733ee74d5d97a51582";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":20,"languages":{"author":"作者: 六根清静","link":"链接: ","source":"来源: 小何blog (记录美好)","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  ClickShowText: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  justifiedGallery: {
    js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
    css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: true
};

var saveToLocal = {
  set: function setWithExpiry(key, value, ttl) {
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-02-15 22:31:58'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = '2'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}})()</script><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"><link rel="stylesheet" href="/css/shuo.css"/><link rel="stylesheet" href="/magnetcss/magnet.css"/><link rel="stylesheet" href="/css/calendar.css"/><link rel="stylesheet" href="//at.alicdn.com/t/font_2060620_l0j6b710zk.css"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/font-awesome-animation.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/macblack.css"><link rel="stylesheet" href="/css/change.css"><link rel="stylesheet" href="/news/css/news.css"/><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="/magnet/css/catalogMagnet.css"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.css"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/iconfont.min.css"><link rel="stykesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/pool.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/><link rel="stylesheet" href="/zan/zan.css"><link rel="stylesheet" href="/swiper/swiper.min.css"><link rel="stylesheet" href="/swiper/swiperstyle.css"><style>#article-container.post-content h1:before, h2:before, h3:before, h4:before, h5:before, h6:before { -webkit-animation: avatar_turn_around 1s linear infinite; -moz-animation: avatar_turn_around 1s linear infinite; -o-animation: avatar_turn_around 1s linear infinite; -ms-animation: avatar_turn_around 1s linear infinite; animation: avatar_turn_around 1s linear infinite; }</style><meta name="generator" content="Hexo 5.0.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="wizard-scene"><div class="wizard-objects"><div class="wizard-square"></div><div class="wizard-circle"></div><div class="wizard-triangle"></div></div><div class="wizard"><div class="wizard-body"></div><div class="wizard-right-arm"><div class="wizard-right-hand"></div></div><div class="wizard-left-arm"><div class="wizard-left-hand"></div></div><div class="wizard-head"><div class="wizard-beard"></div><div class="wizard-face"><div class="wizard-adds"></div></div><div class="wizard-hat"><div class="wizard-hat-of-the-hat"></div><div class="wizard-four-point-star --first"></div><div class="wizard-four-point-star --second"></div><div class="wizard-four-point-star --third"></div></div></div></div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="http://01.027cgb.com/632500/1576904533264.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">138</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">63</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/stars/"><i class="fa-fw fas fa-star faa-shake animated-hover"></i><span> 收藏网址</span></a></div><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-zhuye faa-shake animated-hover"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog.html"><i class="fa-fw iconfont icon-Artboard faa-shake animated-hover"></i><span> 博客</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw iconfont icon-guidang faa-shake animated-hover"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw iconfont icon-biaoqian faa-shake animated-hover"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw iconfont icon-yule1"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/movies/"><i class="fa-fw iconfont icon-yingshi faa-shake animated-hover"></i><span> 影视</span></a></li><li><a class="site-page" href="/games/"><i class="fa-fw iconfont icon-youxi1 faa-shake animated-hover"></i><span> 游戏</span></a></li><li><a class="site-page" href="/galleryGroup"><i class="fa-fw iconfont icon-tuku faa-shake animated-hover"></i><span> 图库</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/messagepad/"><i class="fa-fw iconfont icon-ziyuan6 faa-shake animated-hover"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw iconfont icon-icon_xinyong_xianxing_jijin- faa-shake animated-hover"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw iconfont icon-guanyuwomen faa-shake animated-hover"></i><span> 关于我</span></a></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(http://632500.haituie.cn/632500/v2-d7641be9e2e374ea645eefec144b350e_r.jpg)"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">小何blog (记录美好)</a></span><span id="menus"><div id="search_button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/stars/"><i class="fa-fw fas fa-star faa-shake animated-hover"></i><span> 收藏网址</span></a></div><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-zhuye faa-shake animated-hover"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog.html"><i class="fa-fw iconfont icon-Artboard faa-shake animated-hover"></i><span> 博客</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw iconfont icon-guidang faa-shake animated-hover"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw iconfont icon-biaoqian faa-shake animated-hover"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw iconfont icon-yule1"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/movies/"><i class="fa-fw iconfont icon-yingshi faa-shake animated-hover"></i><span> 影视</span></a></li><li><a class="site-page" href="/games/"><i class="fa-fw iconfont icon-youxi1 faa-shake animated-hover"></i><span> 游戏</span></a></li><li><a class="site-page" href="/galleryGroup"><i class="fa-fw iconfont icon-tuku faa-shake animated-hover"></i><span> 图库</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/messagepad/"><i class="fa-fw iconfont icon-ziyuan6 faa-shake animated-hover"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw iconfont icon-icon_xinyong_xianxing_jijin- faa-shake animated-hover"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw iconfont icon-guanyuwomen faa-shake animated-hover"></i><span> 关于我</span></a></div></div><span class="close" id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></span></span></nav><div id="post-info"><h1 class="post-title">Node.js学习(十一.AJAX技术)</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-02-15T13:49:02.000Z" title="发表于 2021-02-15 21:49:02">2021-02-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-02-15T14:31:58.065Z" title="更新于 2021-02-15 22:31:58">2021-02-15</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%89%8D%E7%AB%AF%E5%AD%A6%E4%B9%A0/">前端学习</a></span></div><div class="meta-secondline"> <span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Node-js学习-十一-AJAX技术-："><a href="#Node-js学习-十一-AJAX技术-：" class="headerlink" title="Node.js学习(十一.AJAX技术)："></a>Node.js学习(十一.AJAX技术)：</h1><blockquote>
<p>本篇文章自己学习的笔记，具体学习请看官方文档:   <a target="_blank" rel="noopener" href="http://nodejs.cn/api/">Node.js API</a></p>
</blockquote>
<h2 id="AJAX技术简介："><a href="#AJAX技术简介：" class="headerlink" title="AJAX技术简介："></a>AJAX技术简介：</h2><ul>
<li><p>AJAX 即 “Asynchronous JavaScript and XML”（异步的 JavaScript 与 XML 技术），指的是一套综合了多项技术的浏览器端网页开发技术。AJAX 的概念由 Jesse James Garrett 所提出，<strong>说白了就可以使用 JavaScript 代码发送网络请求并处理响应，由浏览器实现。</strong></p>
</li>
<li><p>出现的很早 <code>1998</code> 年出来，首次是<code>微软</code>提出来的，并没有引起重视；直到<code>2005</code>年左右，谷歌推出 <code>gmail，gmap</code> 使得ajax技术一时间流行起来。</p>
</li>
<li><p>俗话：<strong>ajax技术就是在页面不刷新情况下，和服务器端进行交互的交互。</strong></p>
</li>
<li><p>传统的 Web 应用允许用户端填写表单（form），当提交表单时就向网页服务器发送一个请求。服务器接收并处理传来的表单，然后送回一个新的网页，但这个做法浪费了许多带宽，因为在前后两个页面中的大部分 HTML 码往往是相同的。由于每次应用的沟通都需要向服务器发送请求，应用的回应时间依赖于服务器的回应时间。这导致了用户界面的回应比本机应用慢得多。</p>
</li>
<li><p>与此不同，AJAX 应用可以仅向服务器发送并取回必须的数据，并在客户端采用 JavaScript 处理来自服务器的回应。因为在服务器和浏览器之间交换的数据大量减少，服务器回应更快了。同时，很多的处理工作可以在发出请求的客户端机器上完成，因此 Web 服务器的负荷也减少了。</p>
</li>
<li><h4 id="特点："><a href="#特点：" class="headerlink" title="特点："></a>特点：</h4><ul>
<li><p><strong>异步请求，局部刷新</strong>。</p>
<ul>
<li><p>同步是指：发送方发出数据后，等接收方发回响应以后才发下一个数据包的通讯方式。</p>
</li>
<li><p>异步是指：发送方发出数据后，不等接收方发回响应，接着发送下个数据包的通讯方式。</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<pre><code>- 局部刷新指刷新页面部分内容。</code></pre>
<hr>
<ul>
<li><h4 id="优缺点："><a href="#优缺点：" class="headerlink" title="优缺点："></a>优缺点：</h4><ul>
<li><strong>优点：</strong>Web 应用程序更为迅捷地回应用户动作，并避免了在网络上发送那些没有改变的信息，减轻服务器压力。</li>
<li><strong>缺点：</strong>浏览器实现之间有差异处理兼容性问题；不能回退和前进；<strong>默认不支持跨域访问</strong>（<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/Security/Same-origin_policy%EF%BC%89%E3%80%82">https://developer.mozilla.org/zh-CN/docs/Web/Security/Same-origin_policy）。</a></li>
</ul>
<hr>
</li>
<li><h4 id="注意事项："><a href="#注意事项：" class="headerlink" title="注意事项："></a><strong>注意事项</strong>：</h4><ul>
<li>ajax 这门技术，必须要在网络协议环境下才可以使用。不能把网页直接拖入到浏览器执行，必须在 web 服务器模式下访问。</li>
<li>总结：<strong>ajax对我们来讲就是书写一段js代码来向服务器发送请求(异步)。</strong></li>
</ul>
</li>
</ul>
<hr>
<h2 id="AJAX书写步骤"><a href="#AJAX书写步骤" class="headerlink" title="AJAX书写步骤:"></a>AJAX书写步骤:</h2><ol>
<li>创建 AJAX 对象；</li>
<li>设置请求路径，请求方式等；</li>
<li>绑定监听状态改变的处理函数，在处理函数可获取响应数据；</li>
<li>发送请求。</li>
</ol>
<h4 id="创建ajax对象会有浏览器兼容性问题："><a href="#创建ajax对象会有浏览器兼容性问题：" class="headerlink" title="创建ajax对象会有浏览器兼容性问题："></a>创建ajax对象会有浏览器兼容性问题：</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createAjax</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> ajax;</span><br><span class="line">    <span class="keyword">try</span> &#123;       <span class="comment">// 非 IE </span></span><br><span class="line">        ajax = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (e) &#123; <span class="comment">// IE</span></span><br><span class="line">        ajax = <span class="keyword">new</span> ActiveXObject(<span class="string">&#x27;Microsoft.XMLHTTP&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ajax;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="响应处理和响应流程"><a href="#响应处理和响应流程" class="headerlink" title="响应处理和响应流程:"></a>响应处理和响应流程:</h2><ul>
<li><p>响应处理，即对服务响应回浏览器的数据根据状态码和 AJAX 对象的状态信息进行不同的处理，在绑定状态改变的处理函数中写对应的逻辑代码即可。</p>
</li>
<li><h4 id="AJAX-对象有-4-个属性："><a href="#AJAX-对象有-4-个属性：" class="headerlink" title="AJAX 对象有 4 个属性："></a>AJAX 对象有 4 个属性：</h4><ul>
<li><code>readyState</code> 总共有 5 个状态值，分别为 0 ~ 4，每个值代表了不同的含义：<code>onreadystatechange</code><ul>
<li>0：初始化，AJAX 对象还没有完成初始化</li>
<li>1：载入，AJAX 对象开始发送请求</li>
<li>2：载入完成，AJAX 对象的请求发送完成</li>
<li>3：解析，AJAX 对象开始读取服务器的响应</li>
<li>4：完成，AJAX 对象读取服务器响应结束</li>
</ul>
</li>
<li><code>status</code> 表示响应的 HTTP 状态码，常见状态码如下：<ul>
<li>200：成功</li>
<li>302：重定向</li>
<li>404：找不到资源</li>
<li>500：服务端错误</li>
</ul>
</li>
<li><code>responseText</code> 获得字符串形式的响应数据。</li>
<li><code>responseXML</code>  获得 XML 形式的响应数据。</li>
</ul>
</li>
<li><p>综合以上，在状态改变的处理函数一般针对 <code>readyState == 4 且 status == 200</code> 的情况才处理，再根据后台返回的数据类型决定从 responseText 或者 responseXML 获取服务器响应回去来的数据。</p>
<p><img src= "/img/loading.gif" data-lazy-src="http://632500.haituie.cn/632500/AJAX%E8%AF%B7%E6%B1%82%E6%B5%81%E7%A8%8B%E5%9B%BE.png" alt="AJAX的请求流程"></p>
</li>
</ul>
<hr>
<h2 id="使用ajax发送get请求："><a href="#使用ajax发送get请求：" class="headerlink" title="使用ajax发送get请求："></a>使用ajax发送get请求：</h2><ul>
<li><p><strong>前端代码：</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>这是首页<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">    欢迎来到我们网站！！ <span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">&quot;obtn&quot;</span>&gt;</span>点击获取数据---点击发送Get请求<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>  <span class="attr">id</span>=<span class="string">&quot;odiv&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">let</span> obtn = <span class="built_in">document</span>.getElementById(<span class="string">&quot;obtn&quot;</span>);</span></span><br><span class="line"><span class="javascript">    <span class="keyword">let</span> odiv = <span class="built_in">document</span>.getElementById(<span class="string">&quot;odiv&quot;</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">    obtn.onclick = <span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">//发送ajax请求</span></span></span><br><span class="line"><span class="javascript">        <span class="comment">// 1、创建 AJAX 对象；</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">let</span> ajax = <span class="keyword">new</span> XMLHttpRequest();</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">// 2、设置请求路径，请求方式等；ajax.open(请求方式，路径)</span></span></span><br><span class="line"><span class="javascript">        ajax.open(<span class="string">&#x27;GET&#x27;</span>, <span class="string">&#x27;/get_data&#x27;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="comment">// 3、绑定监听状态改变的处理函数，在处理函数可获取响应数据；</span></span></span><br><span class="line"><span class="javascript">        ajax.onreadystatechange = <span class="function">()=&gt;</span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="comment">// 获取响应回来的数据</span></span></span><br><span class="line">            if(ajax.readyState===4&amp;&amp; ajax.status===200)&#123;</span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(ajax.readyState);</span></span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(ajax.responseText);</span></span><br><span class="line"><span class="javascript">                <span class="comment">// 请求到数据之后，就可以把数据更新到页面上</span></span></span><br><span class="line">                odiv.innerHTML = ajax.responseText;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"><span class="javascript">        <span class="comment">// 4、发送请求。</span></span></span><br><span class="line">        ajax.send()</span><br><span class="line">    &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>服务端代码：</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">else</span> <span class="keyword">if</span>(requestUrl=== <span class="string">&quot;/get_data&quot;</span>)&#123;       <span class="comment">//或者写成：/get_data.*/.test(requestUrl)</span></span><br><span class="line">    response.setHeader(<span class="string">&quot;Content-type&quot;</span>,<span class="string">&quot;text/html;charset=utf-8&quot;</span>);</span><br><span class="line">    response.write(<span class="string">&quot;这个数据是来自服务器的...&quot;</span>);</span><br><span class="line">    response.end();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><h4 id="避免缓存问题的写法："><a href="#避免缓存问题的写法：" class="headerlink" title="避免缓存问题的写法："></a><strong>避免缓存问题的写法</strong>：</h4><ul>
<li><p>AJAX 能提高页面载入的速度主要的原因是通过 AJAX 减少了重复数据的载入，也就是说在载入数据的同时将数据缓存到内存中，一旦数据被加载其中，只要我们没有刷新页面，这些数据就会一直被缓存在内存中，当我们提交的 URL 与历史的 URL 一致时，就不需要提交给服务器，也就是不需要从服务器上面去获取数据，虽然这样降低了服务器的负载提高了用户的体验，<strong>但是我们不能获取最新的数据。</strong>为了保证我们读取的信息都是最新的，我们就需要禁止他的缓存功能。解决方式有以下几种：</p>
<ul>
<li><strong>在 URL 后面加上一个随机数：Math.random()。</strong></li>
<li><strong>在 URL 后面加上时间搓：new Date().getTime()。</strong></li>
<li><strong>在使用 AJAX 发送请求前加上 ajax.setRequestHeader(‘Cache-Control’, ‘no-cache’)。</strong></li>
</ul>
</li>
<li><p><strong>例如：</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">ajax.open( ..... );</span><br><span class="line"></span><br><span class="line">ajax.setRequestHeader(<span class="string">&#x27;Cache-Control&#x27;</span>, <span class="string">&#x27;no-cache&#x27;</span>);</span><br><span class="line">ajax.send();</span><br></pre></td></tr></table></figure>

</li>
</ul>
</li>
</ul>
<hr>
<h2 id="使用ajax发送post请求："><a href="#使用ajax发送post请求：" class="headerlink" title="使用ajax发送post请求："></a>使用ajax发送post请求：</h2><ul>
<li><p><strong>前端代码：</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">let</span> obtn = <span class="built_in">document</span>.getElementById(<span class="string">&quot;obtn&quot;</span>);</span><br><span class="line">    <span class="keyword">let</span> odiv = <span class="built_in">document</span>.getElementById(<span class="string">&quot;odiv&quot;</span>);</span><br><span class="line">    obtn.onclick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">let</span> username = <span class="built_in">document</span>.getElementById(<span class="string">&quot;username&quot;</span>).value;</span><br><span class="line">        <span class="keyword">let</span> password = <span class="built_in">document</span>.getElementById(<span class="string">&quot;password&quot;</span>).value;</span><br><span class="line">        <span class="keyword">let</span> params = <span class="string">`username=<span class="subst">$&#123;username&#125;</span>&amp;password=<span class="subst">$&#123;password&#125;</span>`</span>;</span><br><span class="line">        <span class="comment">//发送ajax请求</span></span><br><span class="line">        <span class="comment">// 1、创建 AJAX 对象；</span></span><br><span class="line">        <span class="keyword">let</span> ajax = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 2、设置请求路径，请求方式等；ajax.open(请求方式，路径)</span></span><br><span class="line">        ajax.open(<span class="string">&#x27;POST&#x27;</span>, <span class="string">&#x27;/login_post&#x27;</span>);</span><br><span class="line">        </span><br><span class="line">        ajax.setRequestHeader(<span class="string">&quot;enctype&quot;</span>,<span class="string">&quot;application/x-www-form-urlencoded&quot;</span>);</span><br><span class="line">        <span class="comment">// 3、绑定监听状态改变的处理函数，在处理函数可获取响应数据；</span></span><br><span class="line">        ajax.onreadystatechange = <span class="function">()=&gt;</span>&#123;</span><br><span class="line">            <span class="comment">// 获取响应回来的数据</span></span><br><span class="line">            <span class="keyword">if</span>(ajax.readyState===<span class="number">4</span>&amp;&amp; ajax.status===<span class="number">200</span>)&#123;</span><br><span class="line">                <span class="built_in">console</span>.log(ajax.readyState);</span><br><span class="line">                <span class="built_in">console</span>.log(ajax.responseText);</span><br><span class="line">                <span class="comment">// 请求到数据之后，就可以把数据更新到页面上</span></span><br><span class="line">                odiv.innerHTML = ajax.responseText;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 4、发送请求。</span></span><br><span class="line">        ajax.send(params)</span><br><span class="line">    &#125;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>服务端代码：</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">else</span> <span class="keyword">if</span>(requestUrl=== <span class="string">&quot;/login_post&quot;</span>)&#123;   <span class="comment">//来处理css文件的请求   如果这个路径包含.css</span></span><br><span class="line">    request.on(<span class="string">&#x27;data&#x27;</span>,<span class="function">(<span class="params">postData</span>)=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">let</span> uname = postData.toString().split(<span class="string">&quot;&amp;&quot;</span>)[<span class="number">0</span>].split(<span class="string">&quot;=&quot;</span>)[<span class="number">1</span>];   <span class="comment">// 获取用户提交的用户名</span></span><br><span class="line">        <span class="keyword">let</span> pwd = postData.toString().split(<span class="string">&quot;&amp;&quot;</span>)[<span class="number">1</span>].split(<span class="string">&quot;=&quot;</span>)[<span class="number">1</span>];    <span class="comment">// 获取用户提交的密码</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(uname===username &amp;&amp; pwd===password)&#123;</span><br><span class="line">            response.end(<span class="string">&quot;账号密码正确，登录成功&quot;</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            response.end(<span class="string">&quot;账号或者密码错误，登录失败&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><h4 id="超时处理："><a href="#超时处理：" class="headerlink" title="超时处理："></a>超时处理：</h4><ul>
<li><p>有时网络会出现问题或者服务端出问题导致请求时间过长，一般提示网络请求稍后重试，以增加用户的体验感。在代码中我们可以通过定时器和请求中断来实现超时处理的效果。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> timer = <span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 取消请求，中断请求</span></span><br><span class="line">    ajax.abort();</span><br><span class="line">&#125;, <span class="number">5000</span>);</span><br></pre></td></tr></table></figure>

</li>
</ul>
</li>
</ul>
<hr>
<h2 id="方法抽取-了解"><a href="#方法抽取-了解" class="headerlink" title="方法抽取(了解):"></a>方法抽取(了解):</h2><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">mehtod, url, param, success, time</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> ajax;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//处理ajax获取时候的兼容性问题</span></span><br><span class="line">    <span class="keyword">try</span> &#123;       <span class="comment">// 非 IE </span></span><br><span class="line">        ajax = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (e) &#123; <span class="comment">// IE</span></span><br><span class="line">        ajax = <span class="keyword">new</span> ActiveXObject(<span class="string">&#x27;Microsoft.XMLHTTP&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(method === <span class="string">&#x27;get&#x27;</span>)&#123;</span><br><span class="line">        param = <span class="built_in">encodeURI</span>(param);  <span class="comment">//针对get请求的查询参数出现中文的编码处理</span></span><br><span class="line">        url = url + <span class="string">&#x27;?&#x27;</span> + param;</span><br><span class="line">        param = <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    ajax.open(method, url);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(method === <span class="string">&#x27;post&#x27;</span>)&#123;</span><br><span class="line">        ajax.setRequestHeader(<span class="string">&#x27;Content-Type&#x27;</span>, <span class="string">&#x27;application/x-www-form-urlencoded&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ajax.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123; <span class="comment">// onload</span></span><br><span class="line">        <span class="keyword">if</span>(ajax.readyState == <span class="number">4</span> &amp;&amp; ajax.status == <span class="number">200</span>)&#123;</span><br><span class="line">            success(ajax.responseText);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    ajax.send(param);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> timer = <span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        ajax.abort();</span><br><span class="line">    &#125;, time);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="jQuery-中-ajax-方法使用"><a href="#jQuery-中-ajax-方法使用" class="headerlink" title="jQuery 中 ajax 方法使用:"></a>jQuery 中 ajax 方法使用:</h2><ul>
<li><p>async：默认设置下，所有请求均为异步请求。</p>
</li>
<li><p>contentType：发送信息至服务器时内容编码类型，默认为 “application/x-www-form-urlencoded”。</p>
</li>
<li><p><strong>data</strong>：发送到服务器的数据，可以为对象或者 Key=value 格式字符串，若为对象则会自动转换为请求字符串格式。</p>
</li>
<li><p><strong>type</strong>：默认: “GET”，其它 HTTP 请求方法，如 PUT 和 DELETE 也可以使用，但取决浏览器支持。</p>
</li>
<li><p><strong>url</strong>：发送请求的地址，默认当前页地址。</p>
</li>
<li><p>dataType：预期服务器返回的数据类型。如果不指定，jQuery 将自动根据 HTTP 包 MIME 信息来智能判断，比如 XML MIME类型就被识别为 XML，可以不填，可用值：”xml”、”html”、”script”、”json”、”jsonp”、”text”。</p>
</li>
<li><p>cache：默认为 true（dataType 为 script 和 jsonp 时默认为 false，设置为 false 将禁用缓存。</p>
</li>
<li><p>context：这个对象用于设置 AJAX 相关回调函数的上下文。也就是说，让回调函数内 this 的指向（若不指定为当前选项）。</p>
</li>
<li><p>beforeSend：发送请求前调用此函数，可用与如添加自定义 HTTP 头，检查请求参数是否合法。XMLHttpRequest 对象是唯一的参数。若在函数中返回 false 可以取消本次请求。 </p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> (<span class="params">XMLHttpRequest</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// this 默认情况下调用本次 AJAX 请求时传递的 option 对象</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>success</strong>：请求成功后的回调函数，参数：由服务器返回，并根据 dataType 参数进行处理后的数据；描述状态的字符串。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> (<span class="params">data, textStatus</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// data 可能是 xmlDoc, jsonObj, html, text, 等等</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>error：请求失败时调用此函数。有以下三个参数：XMLHttpRequest 对象、错误信息、捕获的异常对象。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> (<span class="params">XMLHttpRequest, textStatus, errorThrown</span>) </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><h4 id="例如："><a href="#例如：" class="headerlink" title="例如："></a>例如：</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">$.ajax(&#123;</span><br><span class="line">    url: <span class="string">&#x27;url&#x27;</span>,</span><br><span class="line">    type: <span class="string">&#x27;GET&#x27;</span>,</span><br><span class="line">    data: &#123;<span class="attr">username</span>:<span class="string">&#x27;zs&#x27;</span>, <span class="attr">password</span>:<span class="string">&#x27;12345&#x27;</span>&#125;,</span><br><span class="line">    success: <span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">        <span class="comment">// 请求成功业务逻辑</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

</li>
</ul>
<hr>
<h2 id="使用-jQuery-发送-GET-方式-AJAX-请求"><a href="#使用-jQuery-发送-GET-方式-AJAX-请求" class="headerlink" title="使用 jQuery 发送 GET 方式 AJAX 请求:"></a>使用 jQuery 发送 GET 方式 AJAX 请求:</h2><ul>
<li><h4 id="使用-ajax-方法"><a href="#使用-ajax-方法" class="headerlink" title="使用.ajax()方法:"></a>使用.ajax()方法:</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">$(<span class="string">&quot;#obtn&quot;</span>).click(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    $.ajax(&#123;</span><br><span class="line">        url:<span class="string">&#x27;/get_data&#x27;</span>,</span><br><span class="line">        data:&#123;<span class="attr">name</span>:<span class="string">&quot;nodejs&quot;</span>&#125;,</span><br><span class="line">        type:<span class="string">&quot;GET&quot;</span>,</span><br><span class="line">        success: <span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(data)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><h4 id="使用-get-方法"><a href="#使用-get-方法" class="headerlink" title="使用.get()方法:"></a>使用.get()方法:</h4><ul>
<li><p><code>url</code>：请求 URL 地址</p>
</li>
<li><p><code>data</code>：请求参数。</p>
</li>
<li><p><code>callback</code>：请求成功时回调函数。</p>
</li>
<li><p><code>type</code>：预期服务器返回的数据类型。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">$.get(<span class="string">&#x27;/get_data&#x27;</span>, &#123;<span class="attr">name</span>:<span class="string">&#x27;nodejs&#x27;</span>, <span class="attr">age</span>:<span class="number">11</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">     <span class="comment">//请求成功的业务逻辑(成功之后的操作)</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

</li>
</ul>
</li>
</ul>
<hr>
<h2 id="使用-jQuery-发送-POST-方式-AJAX-请求："><a href="#使用-jQuery-发送-POST-方式-AJAX-请求：" class="headerlink" title="使用 jQuery 发送 POST 方式 AJAX 请求："></a>使用 jQuery 发送 POST 方式 AJAX 请求：</h2><ul>
<li><h4 id="使用-ajax-方法："><a href="#使用-ajax-方法：" class="headerlink" title="使用.ajax()方法："></a>使用.ajax()方法：</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">$.ajax(&#123;</span><br><span class="line">    url:<span class="string">&quot;/login_post&quot;</span>,</span><br><span class="line">    type:<span class="string">&quot;POST&quot;</span>,</span><br><span class="line">    data: &#123;<span class="attr">username</span>:$(<span class="string">&quot;#username&quot;</span>).val(), <span class="attr">password</span>:$(<span class="string">&quot;#password&quot;</span>).val()&#125;,</span><br><span class="line">    success:<span class="function">(<span class="params">data</span>)=&gt;</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(data);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
</li>
<li><h4 id="使用-post-方法"><a href="#使用-post-方法" class="headerlink" title="使用.post()方法:"></a>使用.post()方法:</h4><ul>
<li><code>url</code>：请求 URL 地址</li>
<li><code>data</code>：请求参数。</li>
<li><code>callback</code>：请求成功时回调函数。</li>
<li><code>type</code>：预期服务器返回的数据类型。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">$.post(<span class="string">&#x27;url&#x27;</span>, &#123;<span class="attr">username</span>:$(<span class="string">&quot;#username&quot;</span>).val(), <span class="attr">password</span>:$(<span class="string">&quot;#password&quot;</span>).val()&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 请求成功业务逻辑</span></span><br><span class="line">    <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

</li>
</ul>
<hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">六根清静</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liugenqingjing2.coding.me/2021/02/15/Node-js%E5%AD%A6%E4%B9%A0-%E5%8D%81%E4%B8%80-AJAX%E6%8A%80%E6%9C%AF/">https://liugenqingjing2.coding.me/2021/02/15/Node-js学习-十一-AJAX技术/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liugenqingjing2.coding.me" target="_blank">小何blog (记录美好)</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E7%B3%BB%E5%88%97%F0%9F%8F%AC/">系列🏬</a><a class="post-meta__tags" href="/tags/Node-js/">Node.js</a></div><div class="post_share"><div class="social-share" data-image="http://632500.haituie.cn/632500/v2-d7641be9e2e374ea645eefec144b350e_r.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏<div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="http://qew58kkb2.hn-bkt.clouddn.com/wechat%20%20%281%29.png" target="_blank"><img class="post-qr-code-img" data-lazy-src="http://qew58kkb2.hn-bkt.clouddn.com/wechat%20%20%281%29.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li></ul></div></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/02/16/Node.js%E5%AD%A6%E4%B9%A0(%E5%8D%81%E4%BA%8C.Express%E6%A1%86%E6%9E%B6(%E4%B8%8A))/"><img class="prev-cover" data-lazy-src="http://632500.haituie.cn/632500/v2-8c6f3ae186be46437013b55b92e90303_r.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Node.js学习(十二.Express框架(上))</div></div></a></div><div class="next-post pull-right"><a href="/2021/02/13/Node-js%E5%AD%A6%E4%B9%A0-%E5%8D%81-Http%E5%8D%8F%E8%AE%AE%E5%92%8CTCP-IP%E6%A8%A1%E5%9E%8B/"><img class="next-cover" data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210213/gXZdd8flwNum.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Node.js学习(十.Http协议和TCP/IP模型)</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2021/01/20/Node-js学习-一-Node-js是什么/" title="Node.js学习(一.Node.js是什么)"><img class="cover" data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210120/oQT*TdzLI^Cl.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-20</div><div class="title">Node.js学习(一.Node.js是什么)</div></div></a></div><div><a href="/2021/01/21/Node-js学习-三-Node-相关工具之NPM上/" title="Node.js学习(三.Node 相关工具之NPM上)"><img class="cover" data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210121/zds0P0Co5RuQ.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-21</div><div class="title">Node.js学习(三.Node 相关工具之NPM上)</div></div></a></div><div><a href="/2021/01/24/Node-js学习-七-常用内置模块（上）/" title="Node.js学习(七.常用内置模块（上）)"><img class="cover" data-lazy-src="http://632500.haituie.cn/632500/v2-eb120a212b30658084a85d5a266b50df_r.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-24</div><div class="title">Node.js学习(七.常用内置模块（上）)</div></div></a></div><div><a href="/2021/02/10/Node-js学习-九-yarn包管理工具与ES6模块化规范/" title="Node.js学习(九.yarn包管理工具与ES6模块化规范)"><img class="cover" data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210210/W3wj^t0Lx1od.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-02-10</div><div class="title">Node.js学习(九.yarn包管理工具与ES6模块化规范)</div></div></a></div><div><a href="/2021/03/14/Node-js学习-二十-Node-js项目流程(上)/" title="Node.js学习(二十.Node.js项目流程(上))"><img class="cover" data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210320/UMp@B^akHmf8.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-14</div><div class="title">Node.js学习(二十.Node.js项目流程(上))</div></div></a></div><div><a href="/2021/03/21/Node-js学习-二十三-跨域介绍和JSONP介绍/" title="Node.js学习(二十三.跨域介绍和JSONP介绍)"><img class="cover" data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210321/qWPEashJOuNK.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-21</div><div class="title">Node.js学习(二十三.跨域介绍和JSONP介绍)</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside_content" id="aside_content"><div class="card-widget card-info"><div class="card-content"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="http://01.027cgb.com/632500/1576904533264.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">六根清静</div><div class="author-info__description">记录美好，记录生活，记录学习</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">138</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">63</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/he_chaoming/dashboard/projects?scope=public&amp;&amp;sort="><i class="fab fa-gofore"></i><span>My Gitee</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/he1213114428" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:484695754@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="tencent://message/?uin=484695754" target="_blank" title="QQ"><i class="fab fa-qq"></i></a></div></div></div><div class="card-widget card-recent-post"><div id="gamenews"><div class="card-content"><div class="item-headline"><i class="fas fa-cube"></i><span>ROLL资讯</span><i class="fas fa-retweet" @click="changetype(current)" style="float:right;margin-top:8px"></i></div><div class="newsbar"><span v-for="(type, index) in listtype" v-on:click="addClass(index)" v-bind:class="{ listtypeon:index==current}">{{type}}</span></div><div class="aside-list"><div class="aside-list-item" v-for="(news,index) in newsvue"><a class="thumbnail" href="javascript:void(0)" @click="getnewsdata(index)" :title="news.title"><img class="loaded" onerror="this.onerror=null;this.src='/img/404.jpg'" data-ll-status="loaded" :src="news.imgList[0]"/></a><div class="content"><a class="title" href="javascript:void(0)" @click="getnewsdata(index)" :title="news.title">{{news.title}}</a><time>{{news.postTime}}</time></div></div></div></div><div id="newsmodal"><button class="modalclose" @click="hidemodle()">关闭</button><h2>{{newpostvue.title}} </h2><h4>{{newpostvue.ptime}} &nbsp;&nbsp; {{newpostvue.source}}</h4><div v-html="newpostvue.content"></div></div></div></div><div class="card-widget card-shuo"><div class="card-content" style="height:auto;min-height:280px;"><div class="item-headline"><i class="fas fa-comments"></i><span>&#x8BF4;&#x8BF4</span><a id="shuovisualchange" style="cursor:pointer;float:right" onclick="shuovisualchange()">编辑</a></div><div id="artitalk_main" style="width:100%;height:100%;padding:10px"></div></div></div><div class="sticky_layout"></div><div class="card-widget card-history"><div class="card-content"><div class="item-headline"><i class="fas fa-paw fa-spin"></i><span>那年今日</span></div><div id="history-news" style="height: 100px;overflow: hidden;"><div id="history-card"></div></div></div></div><div class="card-widget card-announcement"><div class="card-content"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">大学生一枚，软件工程，想做全栈攻城狮，哈哈，有兴趣可以加 QQ:484695754 (也可以点上面的logo)，一起交流学习</div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="card-content"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Node-js%E5%AD%A6%E4%B9%A0-%E5%8D%81%E4%B8%80-AJAX%E6%8A%80%E6%9C%AF-%EF%BC%9A"><span class="toc-number">1.</span> <span class="toc-text">Node.js学习(十一.AJAX技术)：</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#AJAX%E6%8A%80%E6%9C%AF%E7%AE%80%E4%BB%8B%EF%BC%9A"><span class="toc-number">1.1.</span> <span class="toc-text">AJAX技术简介：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%89%B9%E7%82%B9%EF%BC%9A"><span class="toc-number">1.1.0.1.</span> <span class="toc-text">特点：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BC%98%E7%BC%BA%E7%82%B9%EF%BC%9A"><span class="toc-number">1.1.0.2.</span> <span class="toc-text">优缺点：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9%EF%BC%9A"><span class="toc-number">1.1.0.3.</span> <span class="toc-text">注意事项：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#AJAX%E4%B9%A6%E5%86%99%E6%AD%A5%E9%AA%A4"><span class="toc-number">1.2.</span> <span class="toc-text">AJAX书写步骤:</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BAajax%E5%AF%B9%E8%B1%A1%E4%BC%9A%E6%9C%89%E6%B5%8F%E8%A7%88%E5%99%A8%E5%85%BC%E5%AE%B9%E6%80%A7%E9%97%AE%E9%A2%98%EF%BC%9A"><span class="toc-number">1.2.0.1.</span> <span class="toc-text">创建ajax对象会有浏览器兼容性问题：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E5%A4%84%E7%90%86%E5%92%8C%E5%93%8D%E5%BA%94%E6%B5%81%E7%A8%8B"><span class="toc-number">1.3.</span> <span class="toc-text">响应处理和响应流程:</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#AJAX-%E5%AF%B9%E8%B1%A1%E6%9C%89-4-%E4%B8%AA%E5%B1%9E%E6%80%A7%EF%BC%9A"><span class="toc-number">1.3.0.1.</span> <span class="toc-text">AJAX 对象有 4 个属性：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8ajax%E5%8F%91%E9%80%81get%E8%AF%B7%E6%B1%82%EF%BC%9A"><span class="toc-number">1.4.</span> <span class="toc-text">使用ajax发送get请求：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%81%BF%E5%85%8D%E7%BC%93%E5%AD%98%E9%97%AE%E9%A2%98%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9A"><span class="toc-number">1.4.0.1.</span> <span class="toc-text">避免缓存问题的写法：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8ajax%E5%8F%91%E9%80%81post%E8%AF%B7%E6%B1%82%EF%BC%9A"><span class="toc-number">1.5.</span> <span class="toc-text">使用ajax发送post请求：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B6%85%E6%97%B6%E5%A4%84%E7%90%86%EF%BC%9A"><span class="toc-number">1.5.0.1.</span> <span class="toc-text">超时处理：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E6%8A%BD%E5%8F%96-%E4%BA%86%E8%A7%A3"><span class="toc-number">1.6.</span> <span class="toc-text">方法抽取(了解):</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jQuery-%E4%B8%AD-ajax-%E6%96%B9%E6%B3%95%E4%BD%BF%E7%94%A8"><span class="toc-number">1.7.</span> <span class="toc-text">jQuery 中 ajax 方法使用:</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BE%8B%E5%A6%82%EF%BC%9A"><span class="toc-number">1.7.0.1.</span> <span class="toc-text">例如：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-jQuery-%E5%8F%91%E9%80%81-GET-%E6%96%B9%E5%BC%8F-AJAX-%E8%AF%B7%E6%B1%82"><span class="toc-number">1.8.</span> <span class="toc-text">使用 jQuery 发送 GET 方式 AJAX 请求:</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-ajax-%E6%96%B9%E6%B3%95"><span class="toc-number">1.8.0.1.</span> <span class="toc-text">使用.ajax()方法:</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-get-%E6%96%B9%E6%B3%95"><span class="toc-number">1.8.0.2.</span> <span class="toc-text">使用.get()方法:</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-jQuery-%E5%8F%91%E9%80%81-POST-%E6%96%B9%E5%BC%8F-AJAX-%E8%AF%B7%E6%B1%82%EF%BC%9A"><span class="toc-number">1.9.</span> <span class="toc-text">使用 jQuery 发送 POST 方式 AJAX 请求：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-ajax-%E6%96%B9%E6%B3%95%EF%BC%9A"><span class="toc-number">1.9.0.1.</span> <span class="toc-text">使用.ajax()方法：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-post-%E6%96%B9%E6%B3%95"><span class="toc-number">1.9.0.2.</span> <span class="toc-text">使用.post()方法:</span></a></li></ol></li></ol></li></ol></li></ol></div></div></div><div class="card-widget card-recent-post"><div class="card-content"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/03/21/Node-js%E5%AD%A6%E4%B9%A0-%E4%BA%8C%E5%8D%81%E4%B8%89-%E8%B7%A8%E5%9F%9F%E4%BB%8B%E7%BB%8D%E5%92%8CJSONP%E4%BB%8B%E7%BB%8D/" title="Node.js学习(二十三.跨域介绍和JSONP介绍)"><img data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210321/qWPEashJOuNK.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Node.js学习(二十三.跨域介绍和JSONP介绍)"/></a><div class="content"><a class="title" href="/2021/03/21/Node-js%E5%AD%A6%E4%B9%A0-%E4%BA%8C%E5%8D%81%E4%B8%89-%E8%B7%A8%E5%9F%9F%E4%BB%8B%E7%BB%8D%E5%92%8CJSONP%E4%BB%8B%E7%BB%8D/" title="Node.js学习(二十三.跨域介绍和JSONP介绍)">Node.js学习(二十三.跨域介绍和JSONP介绍)</a><time datetime="2021-03-21T13:40:58.000Z" title="发表于 2021-03-21 21:40:58">2021-03-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/03/20/Node-js%E5%AD%A6%E4%B9%A0-%E4%BA%8C%E5%8D%81%E4%BA%8C-Node-js%E9%A1%B9%E7%9B%AE%E6%B5%81%E7%A8%8B-%E4%B8%8B/" title="Node.js学习(二十二.Node.js项目流程(下))"><img data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210320/CvAoe6kC5*f2.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Node.js学习(二十二.Node.js项目流程(下))"/></a><div class="content"><a class="title" href="/2021/03/20/Node-js%E5%AD%A6%E4%B9%A0-%E4%BA%8C%E5%8D%81%E4%BA%8C-Node-js%E9%A1%B9%E7%9B%AE%E6%B5%81%E7%A8%8B-%E4%B8%8B/" title="Node.js学习(二十二.Node.js项目流程(下))">Node.js学习(二十二.Node.js项目流程(下))</a><time datetime="2021-03-20T14:33:29.000Z" title="发表于 2021-03-20 22:33:29">2021-03-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/03/15/Node-js%E5%AD%A6%E4%B9%A0-%E4%BA%8C%E5%8D%81%E4%B8%80-Node-js%E9%A1%B9%E7%9B%AE%E6%B5%81%E7%A8%8B-%E4%B8%AD/" title="Node.js学习(二十一.Node.js项目流程(中))"><img data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210320/gSrAfCznw@^F.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Node.js学习(二十一.Node.js项目流程(中))"/></a><div class="content"><a class="title" href="/2021/03/15/Node-js%E5%AD%A6%E4%B9%A0-%E4%BA%8C%E5%8D%81%E4%B8%80-Node-js%E9%A1%B9%E7%9B%AE%E6%B5%81%E7%A8%8B-%E4%B8%AD/" title="Node.js学习(二十一.Node.js项目流程(中))">Node.js学习(二十一.Node.js项目流程(中))</a><time datetime="2021-03-15T04:35:12.000Z" title="发表于 2021-03-15 12:35:12">2021-03-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/03/14/Node-js%E5%AD%A6%E4%B9%A0-%E4%BA%8C%E5%8D%81-Node-js%E9%A1%B9%E7%9B%AE%E6%B5%81%E7%A8%8B(%E4%B8%8A)/" title="Node.js学习(二十.Node.js项目流程(上))"><img data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210320/UMp@B^akHmf8.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Node.js学习(二十.Node.js项目流程(上))"/></a><div class="content"><a class="title" href="/2021/03/14/Node-js%E5%AD%A6%E4%B9%A0-%E4%BA%8C%E5%8D%81-Node-js%E9%A1%B9%E7%9B%AE%E6%B5%81%E7%A8%8B(%E4%B8%8A)/" title="Node.js学习(二十.Node.js项目流程(上))">Node.js学习(二十.Node.js项目流程(上))</a><time datetime="2021-03-14T14:36:58.000Z" title="发表于 2021-03-14 22:36:58">2021-03-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/02/27/Node-js%E5%AD%A6%E4%B9%A0-%E5%8D%81%E4%B9%9D-%E5%B0%81%E8%A3%85%E6%93%8D%E4%BD%9C%E6%95%B0%E6%8D%AE%E5%BA%93%E5%92%8CCSRF/" title="Node.js学习(十九.封装操作数据库和CSRF)"><img data-lazy-src="https://gitee.com/he_chaoming/blog_tuchuang/raw/master/20210227/EcgLTE4WPOp^.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Node.js学习(十九.封装操作数据库和CSRF)"/></a><div class="content"><a class="title" href="/2021/02/27/Node-js%E5%AD%A6%E4%B9%A0-%E5%8D%81%E4%B9%9D-%E5%B0%81%E8%A3%85%E6%93%8D%E4%BD%9C%E6%95%B0%E6%8D%AE%E5%BA%93%E5%92%8CCSRF/" title="Node.js学习(十九.封装操作数据库和CSRF)">Node.js学习(十九.封装操作数据库和CSRF)</a><time datetime="2021-02-27T13:20:18.000Z" title="发表于 2021-02-27 21:20:18">2021-02-27</time></div></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By 六根清静</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi,  welcome  to  my  <a  href="">blog</a>!</div><div class="icp"><a><img class="icp-icon" src="/img/icp.png" alt="ICP"/><span>豫ICP备2020025430号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module" defer></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> {preloader.endLoading()})
setTimeout(function(){preloader.endLoading();}, 50000);</script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    let initData = {
      el: '#vcomment',
      appId: 'kW2ft895T235y7DxmyJmXX5X-MdYXbMMI',
      appKey: 'v0zBPCAdwiJ0xg4s4eSfusLD',
      placeholder: '建议使用QQ邮箱，评论头像采用QQ头像',
      avatar: 'monsterid',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: false,
      serverURLs: 'https://???????.api.lncldglobal.com',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: true,
      path: window.location.pathname,
      master: '1f76478c4ec918ffc6d50de6b68db531'.split(','),
      friends: '5c?????bfe6rfc72a????e268ad3819c,7c?????bfe65fc02a????e2????3919c'.split(','),
      tagMeta: '博主,小伙伴,访客'.split(',')
    }

    if (true) { 
      initData.requiredFields= ('nick,mail'.split(','))
    }
    
    if (false) {
      const otherData = false
      initData = Object.assign({}, initData, otherData)
    }
    
    const valine = new Valine(initData)
  }

  if (typeof Valine === 'function') initValine() 
  else $.getScript('https://cdn.jsdelivr.net/gh/HCLonely/Valine@latest/dist/Valine.min.js', initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.querySelector('#vcomment'),loadValine)
  else setTimeout(() => loadValine(), 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script src='https://cdn.jsdelivr.net/npm/artitalk'></script><script> $(".category-list-count").prepend("<i class=\"fas fa-book\"></i>");</script><script src="/js/list.js"></script><script src="/js/gitcalendar.js"></script><script src="/js/calendar.js"></script><script src="/js/xkTool.js"></script><script src="/js/pjax.js"></script><script src="/magnet/js/vue.min.js"></script><script src="/magnet/js/catalogMagnet.js"></script><script src="/js/airvisualapi.js"></script><script src="/js/history.js"></script><script src="/js/historyroll.js"></script><script src="/js/change.js"></script><script type="text/javascript" src="https://www.airvisual.com/scripts/widget_v2.0.js"></script><script> setTimeout(function(){$('.monoline').eq(0).html($(".monoline strong").eq(0).text().replace('°','℃'));},5000);</script><script src="https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/js/mouse_snow.min.js"></script><script src="/js/myBg.js"></script><script src="/js/shuo.js"></script><script src="/js/artitalkkey.js"></script><script src="/news/js/keys.js"></script><script src="/news/js/news.js"></script><script src="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/js/pool.min.js"><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="/stars/stars.js"></script><script src="https://cdn1.lncld.net/static/js/3.5.0/av-min.js"></script><script src="/zan/zan.js"></script><div class="aplayer no-destroy" data-id="2916766519" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="false" muted></div><script src="/swiper/swiper.min.js"></script><script src="/swiper/swiperindex.js"></script><script async src="//at.alicdn.com/t/font_2264842_3izu8i5eoc2.js"></script><canvas class="fireworks" mobile="false"></canvas><script src="/js/third-party/fireworks.js"></script><script src="/js/third-party/activate-power-mode.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script>(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/6fdec148.js","daovoice")
</script><script>var isChatBtn = true
daovoice('init', {
  app_id: '6fdec148',},{
  launcher: { 
     disableLauncherIcon: isChatBtn // 悬浮 ICON 是否显示
  },
});
daovoice('update');

if (isChatBtn) {
  var chatBtnFn = () => {
    var chatBtn = document.getElementById("chat_btn")
    chatBtn.addEventListener("click", function(){
      daovoice('show')
    });
  }
  chatBtnFn()
} else {
  if (true) {
    function chatBtnHide () {
      daovoice('update', {},{
        launcher: { 
        disableLauncherIcon: true // 悬浮 ICON 是否显示
        },
      });
    }
    function chatBtnShow () {
      daovoice('update', {},{
        launcher: { 
        disableLauncherIcon: false // 悬浮 ICON 是否显示
        },
      });
    }
  }
}</script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"hHeadPos":0.5,"vHeadPos":0.618,"jsonPath":"/live2dw/assets/unitychan.model.json"},"display":{"superSample":2,"width":150,"height":300,"position":"right","hOffset":0,"vOffset":-20},"mobile":{"show":true,"scale":0.6},"react":{"opacityDefault":0.7,"opacityOnHover":0.8},"log":false});</script></body></html>